package thread.java20230112;

import java.util.concurrent.CyclicBarrier;

/**
 * Cyclic
 */
public class Demo54 {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(4, ()->{
            System.out.println("所有玩家准备就绪, 开始游戏");
        });
        Runnable runnable = ()->{
            for (int i = 0; i < 2; i++) {
                try {
                    String name = Thread.currentThread().getName();
                    Thread.sleep((long) (Math.random() * 3000));//每个玩家需要准备一段时间 0-3秒
                    System.out.println(name+"已经准备就绪, 等待其他玩家");
                    barrier.await();//已经到达栅栏, 等待其他线程
                    //开始玩游戏
                    Thread.sleep((long) (Math.random() * 3000));
                    System.out.println(name + "游戏结束.");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        };
        for (int i = 0; i < 4; i++) {
            new  Thread(runnable,"玩家"+ i).start();
        }
    }
}
